let json = require('koa-json');
let i18n = require('koa-i18n');
let views = require('koa-views');
let koaBody = require('koa-body');
let serve = require('koa-static');
let logger = require('koa-logger');
let locale = require('koa-locale');
let convert = require('koa-convert');
// let redisStore = require('koa-redis');
let koaOnError = require('koa-onerror');
let bodyParser = require('koa-bodyparser');
let session = require('koa-generic-session');

let routes = require('../routes');
let baseContext = require('./BaseContext');
let authHandler = require('./AuthHandler');
let errorHandler = require('./GlobalErrorHandler');


module.exports = function (app, config) {
    baseContext(app);
    app.use(convert(bodyParser()));
    app.use(koaBody());
    app.use(convert(json()));
    app.keys = ['keys', 'futu-keys'];

   // config.session.store = redisStore(config.redis);
    app.use(convert(session(config.session)));
  // logger
    app.use(convert(logger()));

    // static file serving
    app.use(serve(config.static_dir.root,config.static_dir.options));

    // initialize render helper,must be used before any router is used
    app.use(views(config.template.path, config.template.options));

    //i18n
    locale(app);
    app.use(i18n(app, {
        directory: config.i18n.directory,
        locales: config.i18n.locales, // defualtLocale
        query: true
    }));
    app.use(errorHandler());
    app.use(authHandler());

    // set up actions with routes
    routes(app);

    // 500 error
    koaOnError(app, { template: config.template.path + '/500.html' });

    // 404
    app.use(async function(ctx) {
        ctx.status = 404;
        await ctx.render('404');
    });
};
